<?php 

class ContentScope extends AppModel
{
	var $name = 'ContentScope';
	
	const ORDER_ASC = "ASC";
	const ORDER_DESC = "DESC";
	var $fieldProperties = array(
	
		'title' => array(
			'type' => 'text',
			'group' => 'add',
			'validate'=>VALID_NOT_EMPTY
		),
		
		'model' => array(
			'type' => 'select',
			'group' => 'add',
			'label' => 'Content Type',
			'empty' => '-Select-',
			'options' => array('Listing'=>'Listings', 'Review'=>'Reviews', 'User' => 'Users', 'ReviewComment'=>'ReviewComments'),
			'triggers' => array('onChange' => array('update' => array('order_by','sort_order')))
		),
	
		'conditions' => array(
			'type' => 'parent', 
			'childInfo' => array(
				'model' => 'ContentScopeCondition',
				'child_group' => 'add',
				'allowMultiple' => true
			),
			'group' => 'add',
			'fieldModifier' => 'toggleSerialized'
		),
		
		'order_by' => array(
			'type' => 'select',
			'group' => 'add',
		),
		'sort_order' => array(
			'type' => 'select',
			'group' => 'add',
		),
    'randomize' => array(
        "type"=>"checkbox",
        "label" => "Randomize result",
        'group' => 'add',
    )
	
	);
	
	/*
	var $belongsTo = array(
        'Content' => array(
			'class' =>'Content',
        	//'counterCache' => true
		)
    );*/
    
    var $fieldsForUserManipulation = array(
		'Listing' => array(
			'order_by' => array('created', 'title', 'userAvg', 'editorialAvg', 'views_count', 'review_count'),
			//'condition' => array('list_category_id', 'is_featured', 'is_editorial')
    		'publishedScope'=>"published",
    		'recursive'=>-1
    	),
    	'Review'=>array(
    		'order_by'=> array('created', 'vote_count', 'avg_score','review_comment_count'),
    		'publishedScope'=>"published",
    		'recursive'=>0
    	),
    	"User"=>array(
    		'publishedScope'=>"activated",
    		'order_by'=>array('username','last_login_date','created','review_count','listing_count','listing_asset_count','review_comment_count'),
    		'recursive'=>-1
    	),
    	"ReviewComment"=>array(
    		'publishedScope'=>"published",
    		'order_by'=>array('created'),
    		'recursive'=>0
    	)
	);
    function initialize()
    {
    	$this->fieldProperties['model']['validate'] = array('rule'=>array('inList',array_keys($this->fieldProperties['model']['options'])),'empty'=>false);
    	$this->fieldProperties['sort_order']['options'] = $this->getSortOrderOptions();
    	parent::initialize();
    }
    
    function afterInitialize()
    {
    	$fieldProperties = $this->fieldProperties;
    	foreach($fieldProperties as $field=>$properties)
    	{
    		if(isset($properties['options']))
    		{
	    		foreach($properties['options'] as $value=>$label)
	    		{
	    			$newOptionList[$value] = __($label);
	    		}
    			if(isset($properties['empty']))
	    		{
	    			$this->fieldProperties[$field]['empty'] = __($properties['empty']);
	    		}
	    		$this->fieldProperties[$field]['options'] = $newOptionList;
	    	}
	    	$newOptionList = array();
	    } 
    	parent::afterInitialize();	
    }
    
	function getOrderByOptions($content)
	{
		if(!$content)
		{
			return array();
		}
		//$content = Inflector::singularize($content);
		$this->Listing = cri('Listing');
		$this->Review = cri('Review');
		$this->User = cri('Users.User');
		$this->ReviewComment = cri('ReviewComment');
 		$fields = $this->fieldsForUserManipulation[$content]['order_by'];
		$newOptions = array();
			
		foreach($fields as $field)
		{
			$label = $this->{$content}->getFieldProperty($field, 'label');
			if(is_null($label))
			{
				$label = Inflector::humanize($field);
			}
			$newOptions[$field] = __($label);
		}
		
		$editorReviewDisabled = cr('GeneralConfig.disable_editor_reviews');
		if($editorReviewDisabled)
		{
			unset($newOptions['editorialAvg']);
		}
		
		if(cr('ReviewConfig.allow_comment') != '1')
		{	
			if($content != 'Listing')
			{
				unset($newOptions['review_comment_count']);
			}
		}		
		return $newOptions;
	}
	
	function getSortOrderOptions($content = null)
	{
		return array(self::ORDER_DESC=>__("Descending"),self::ORDER_ASC => __("Ascending"));
	}
	/**
	 * get records for conten modules.
	 * pass array('model'=>"Model",'scope'=>"","limit"=>)
	 * @param $params
	 */
	function getContent($params,$presentUrl = array())
	{
		$entity_plural = low(Inflector::pluralize($params['model']));
		$records = array();
		$limit = $params['limit'];
		$categoryId = null;
		$categoryId = null;
		if(($presentUrl['controller'] == "categories" && $presentUrl['action']== "view"))
		{
			$categoryId = $presentUrl['pass'][0];
		}
		if(isset($presentUrl['named']['category']))
		{
			$categoryId = $presentUrl['named']['category'];
		}
		if($categoryId)
		{
			$categoryId = cri('ListCategory')->field('id',array('slug'=>$categoryId));
		}

		if(is_numeric($params['scope']))
		{
			$model = Utility::getModelObject($params['model']);
			$conditions = array('ContentScope.id' => $params['scope']);

			$findInfo = cri('ContentScope')->find('first', compact('conditions'));
			$conditions = array();
			
			$callbackFn = 'get'.$findInfo['ContentScope']['model'].'Conditions';
			if(method_exists($this,$callbackFn))
			{
				$conditions = $this->$callbackFn($findInfo,$categoryId);
			}else
			{
				if($findInfo['ContentScope']['model'] != 'User' && is_array($findInfo['ContentScope']['conditions']))
				{
					foreach($findInfo['ContentScope']['conditions'] as $condition)
					{
						if($condition['field'] =='list_category_id' && @$condition['value'] == "autodetect" )
						{
							if(!$categoryId)
							{
								return false;
							}
							$condition['value'] = 	$categoryId;
						}else
						{
							$categoryIds  = array();
							if(isset($condition['value']))
							{
								$categoryIds =  cri('ListCategory')->getCategoryTreeList($condition['value']);
							}
							$categoryIds  = array_flip($categoryIds);
							if(isset($condition['value']))
							{
								array_push($categoryIds, $condition['value']);
							}
							$condition['value'] = array_values($categoryIds);
						}
						if($condition['field'] && isset($condition['value']))
						{
                            if($condition['field'] =='list_category_id' && $model->alias == "Listing" && cr('ListingConfig.allow_multiple_categories'))
                            {
								$conditions['OR']['AdditionalCategory.list_category_id'] = $condition['value'];
								$joins[0] = array(
									"alias" => "AdditionalCategory",
									"table" => cri("AdditionalCategory")->table,
									"conditions" => array("AdditionalCategory.listing_id = Listing.id"),
									"type" => "LEFT",
									"foreignKey" => false
								);
								$group = "Listing.id";	
								$conditions['OR'][] = array($model->alias.'.'.$condition['field'] => $condition['value']);
                            }else
                            {
                                $conditions[] = array($model->alias.'.'.$condition['field'] => $condition['value']);
                            }
						}
					}
				}
			}
			$order = $findInfo['ContentScope']['order_by'];
			$sortOrder = null;
			if($findInfo['ContentScope']['sort_order'] && in_array($findInfo['ContentScope']['sort_order'],array_keys($this->getSortOrderOptions())))
			{
				$sortOrder = $findInfo['ContentScope']['sort_order'];
			}
			$scope = null;
			if(isset($this->fieldsForUserManipulation[$model->alias]['publishedScope']))
			{
				$scope = $this->fieldsForUserManipulation[$model->alias]['publishedScope'];
			}
			if(in_array($order,$this->fieldsForUserManipulation[$model->alias]['order_by']) == false)
			{
				$order  = null;
			}else
			{
				$order = $model->alias.'.'.$order;
				if($sortOrder)
				{
					$order .= ' '.$sortOrder; 
				}
			}
			$recursive = null;
			//if $conditions is false then we will ignore conditions.
			if($conditions !== false)
			{
				if(isset($this->fieldsForUserManipulation[$model->alias]['recursive']))
				{
					$recursive = $this->fieldsForUserManipulation[$model->alias]['recursive'];
				}
				$model->setScope($scope);
        $queryType = "all";
        if(isset($findInfo['ContentScope']['randomize']) && $findInfo['ContentScope']['randomize'])
        {
            $queryType = "randomRecords";
        }
				$records = $model->find($queryType, compact('conditions', 'order','limit','recursive','scope','joins','group'));
				//to prevnet scope from appying in other queries.
				$model->clearScope($scope);
			}
			
		}
		elseif(is_string($params['scope']))
		{
			$indexMethod = $params['scope'];
			$url = '/'.$entity_plural.'/index/'.$indexMethod;
			$records = $this->requestAction($url, array('named' => array('limit' => $limit), 'vars' => true));
		}
		return $records;
	}	
	
	protected function getReviewConditions($findInfo,$categoryId)
	{
		$conditions = array();
		foreach($findInfo['ContentScope']['conditions'] as $condition)
		{
			if($condition['field'] =='list_category_id' && $condition['value'] == "autodetect" )
			{
						if(!$categoryId)
						{
							return false;
						}
						$condition['value'] = 	$categoryId;
			}
			if(cr('GeneralConfig.disable_editor_reviews') && $condition['field'] == "is_editorial")
			{
				$conditions = false;
				continue;
			}
			if($condition['field'] && isset($condition['value']))
			{
				$conditions['Review.'.$condition['field']] = $condition['value'];
			}
		}
		return $conditions;
	}
	protected function getReviewCommentConditions($findInfo,$categoryId)
	{
		$conditions = array();
		if(is_array($findInfo['ContentScope']['conditions']))
		{
			foreach($findInfo['ContentScope']['conditions'] as $condition)
			{
				if($condition['field'] =='list_category_id' && isset($condition) && $condition['value'] == "autodetect" )
				{
					if(!$categoryId)
					{
						return false;
					}
					$condition['value'] = 	$categoryId;
				}
				if($condition['field'] && isset($condition['value']))
				{
					$conditions[]['Review.'.$condition['field']][] = $condition['value'];
				}
			}
		}
		return $conditions;
	}
}

?>